package com.base.gsyvideoplayer.tools;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.base.common.utils.OnClickCheckedUtil;
import com.base.common.utils.UIUtils;
import com.base.common.utils.mimeType.MimeType;
import com.base.common.view.widget.imageView.ImageLoaderUtils;
import com.base.gsyvideoplayer.R;
import com.base.gsyvideoplayer.model.SwitchVideoModel;
import com.base.gsyvideoplayer.view.SampleVideo;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;

import java.util.HashMap;
import java.util.List;


public class GSYSampleVideoUtils {

    public boolean isPlay;
    public boolean isPause;
    private boolean isRelease;

    private OrientationUtils orientationUtils;

    private MediaMetadataRetriever mCoverMedia;

    private ImageView coverImageView;
    private Activity activity;

    private SampleVideo detailPlayer;


    public GSYSampleVideoUtils(Activity activity) {
        this.activity = activity;
    }

    public void initView(final SampleVideo detailPlayer) {
        this.detailPlayer = detailPlayer;

//        detailPlayer.setUp(url, true, "");
        resolveNormalVideoUI();
        //增加封面
        coverImageView = new ImageView(activity);
        coverImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        //coverImageView.setImageResource(R.mipmap.xxx1);
        detailPlayer.setThumbImageView(coverImageView);

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(activity, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        detailPlayer.setIsTouchWiget(true);
        //detailPlayer.setIsTouchWigetFull(false);
        //关闭自动旋转
        detailPlayer.setRotateViewAuto(false);
        detailPlayer.setLockLand(false);

        //打开  实现竖屏全屏动画
        detailPlayer.setShowFullAnimation(true);
        detailPlayer.setType(3);
        detailPlayer.getLayout_top().setPadding(0, 50, 0, 0);
        detailPlayer.setNeedLockFull(true);
        detailPlayer.setSeekRatio(1);
        detailPlayer.getBackButton().setOnClickListener(new OnClickCheckedUtil() {
            @Override
            public void onClicked(View view) {
                activity.finish();
            }
        });
        //detailPlayer.setOpenPreView(false);
        detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(activity, true, true);
                //屏蔽，实现竖屏全屏
                orientationUtils.resolveByClick();
            }
        });

        detailPlayer.setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                //开始播放了才能旋转和全屏
                //orientationUtils.setEnable(true);
                orientationUtils.setEnable(false);
                isPlay = true;
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                super.onClickStartError(url, objects);
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                //屏蔽，实现竖屏全屏
                //if (orientationUtils != null) {
                //orientationUtils.backToProtVideo();
                //}
            }
        });

        detailPlayer.setLockClickListener(new LockClickListener() {
            @Override
            public void onClick(View view, boolean lock) {
                //屏蔽，实现竖屏全屏
                //if (orientationUtils != null) {
                //配合下方的onConfigurationChanged
                //orientationUtils.setEnable(!lock);
                //}
            }
        });


//        loadFirstFrameCover(url);
    }

    public void initUrl(List<SwitchVideoModel> url, String... poster) {
        if (url == null || url.size() == 0) return;
        if (poster.length > 0) {
            ImageLoaderUtils.loadImage(coverImageView, poster[0]);
        }
        detailPlayer.setUp(url, true, "");
    }


    /**
     * 返回键
     *
     * @return
     */
    public boolean onBackPressed() {

        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }

        if (GSYVideoManager.backFromWindowFull(activity)) {
            return true;
        }

        return false;
    }


    public void onPause() {
        GSYVideoPlayer videoPlayer = getCurPlay();
        if (videoPlayer != null)
            videoPlayer.onVideoPause();
        isPause = true;
    }

    public void onResume() {
        GSYVideoPlayer videoPlayer = getCurPlay();
        if (videoPlayer != null) videoPlayer.onVideoResume();
        isPause = false;
    }

    public void onDestroy() {
        isRelease = true;
        if (isPlay) {
            GSYVideoPlayer videoPlayer = getCurPlay();
            if (videoPlayer != null)
                videoPlayer.release();
        }
        //GSYPreViewManager.instance().releaseMediaPlayer();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
        if (mCoverMedia != null) {
            mCoverMedia.release();
            mCoverMedia = null;
        }
    }

    public void onConfigurationChanged(Configuration newConfig) {
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(activity, newConfig, orientationUtils, true, true);
        }
        //竖屏全屏
        orientationUtils.setEnable(false);
    }


    public GSYVideoPlayer getCurPlay() {
        if (detailPlayer != null && detailPlayer.getFullWindowPlayer() != null) {
            return detailPlayer.getFullWindowPlayer();
        }
        return detailPlayer;
    }


    private void resolveNormalVideoUI() {
        //增加title
        detailPlayer.getTitleTextView().setVisibility(View.GONE);
//        detailPlayer.getBackButton().setVisibility(View.GONE);
    }

    /**
     * 这里只是演示，并不建议直接这么做
     * MediaMetadataRetriever最好做一个独立的管理器
     * 使用缓存
     * 注意资源的开销和异步等
     *
     * @param url 缩略图地址
     */
    public void loadFirstFrameCover(String url) {
        if (TextUtils.isEmpty(url)) return;
        ImageLoaderUtils.loadImage(coverImageView, url, false);
    }


    /**
     * 视频地址
     *
     * @param url
     */
    public void loadFirstFrameCoverForVideo(String url) {
        if (url == null) return;
        if (MimeType.isVideoType(url)) {
            ImageLoaderUtils.loadImage(coverImageView, url, false);
        }
    }


    public MediaMetadataRetriever getMediaMetadataRetriever(String url) {
        if (mCoverMedia == null) {
            mCoverMedia = new MediaMetadataRetriever();
        }

        try {
            mCoverMedia.setDataSource(url, new HashMap<String, String>());
        } catch (Exception e) {
            if (e instanceof RuntimeException) {

            }
        }

//        String rotation = mCoverMedia.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);//获取视频方向
//        String rotation = mCoverMedia.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION);//获取视频时长 毫秒

        return mCoverMedia;
    }

}
